<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-02-27
 * Time: 15:28
 */

namespace app\common\model;
use think\Db;

class Hierarchy extends Catalog
{
    private const TAB_NAME          = "hierarchy";
    private const TAB_DETAILS_NAME  = 'hierarchy_details';

    public function __construct()
    {
        parent::__construct(self::TAB_NAME);
    }

    /**
     * 获取层级详细信息
     * @author 王海东
     * @date
     * @param int $gid  层级id
     * @return array
     */
    public function infoHierarchy(int $gid)
    :array {
        $data = $this->info($gid);

        return $data;
    }

    /**
     * 以id作为下标获取所有层级名称
     * @author 王海东
     * @date
     * @return array
     */
    public function getHierarchy()
    :array {
       return Db::name(self::TAB_NAME)
            ->column('id,title');
    }

    /**
     * 层级列表
     * @author 王海东
     * @param int  $pgid         层级id
     * @param bool $onlyChild       是否只返回直接子层级
     * @return array
     * @throws
     */
    public function listHierarchy(int $pgid = 0,bool $onlyChild = false)
    :array {

        $pInfo = Db::name(self::TAB_NAME)
                   ->field([
                       "ln",
                       "rn",
                   ])
                   ->where("id", $pgid)
                   ->find();
        if (!$pInfo) {
            throw new \Exception("父层级不存在");
        }

        $db = Db::name(self::TAB_NAME)
                ->alias("h")
                ->field([
                    "h.id",
                    "h.title",
                    "h.pid",
                ])
                ->where("h.ln", ">=", $pInfo["ln"])
                ->where("h.rn", "<=", $pInfo["rn"]);
        if ($onlyChild) {
            $db->where("h.pid", $pgid);
        }

        $list = $db->leftJoin(self::TAB_DETAILS_NAME." hd","h.id = hd.id")
                   ->select();
        if (!$list) {
            return [];
        }

        //整理成树型
        if (!$onlyChild) {
            $list = $this->generateTree($list);
        }

        return $list;
    }

    /**
     * 添加层级
     * @author 王海东
     * @date
     * @param string $title
     * @param string $pid
     * @return int
     * @throws \Exception
     */
    public function addHierarchy(string $title,string $pid = null)
    :int {
        Db::startTrans();
        try {
            $hid = $this->add($title, $pid);

            Db::name(self::TAB_DETAILS_NAME)
              ->insert([
                  "hierarchy_id" => $hid,
              ]);

        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }

        Db::commit();
        return $hid;
    }

    /**
     * 修改层级
     * @author 王海东
     * @date
     * @param string $title 层级名称
     * @param int    $id    层级id
     * @return bool
     * @throws \Exception
     */
    public function editHierarchy(string $title,int $id)
    :bool {
        $update = [];

        if(isset($title)) {
            $update['title'] = $title;
        }

        try {
            return Db::name(self::TAB_NAME)
              ->where('id',$id)
              ->update($update) ? true : false;
        } catch (\Exception $e) {
            throw new \Exception('修改失败');
        }
    }

    /**
     * 删除层级
     * @author 王海东
     * @date
     * @param int $id   层级id
     * @return bool
     * @throws \Exception
     */
    public function delHierarchy(int $id)
    :bool {
        Db::startTrans();
        try {

            $rows = $this->del($id);

            Db::name(self::TAB_DETAILS_NAME)
              ->where("hierarchy_id", $id)
              ->delete();

        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception("层级删除失败");
        }
        Db::commit();
        return $rows ? true : false;
    }
}